package cn.samler.shopapi.Controller;

import cn.samler.shopapi.Entity.Address;
import cn.samler.shopapi.Entity.User;
import cn.samler.shopapi.Model.Sys.Response;
import cn.samler.shopapi.Service.AddressService;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/address")
public class AddressController {
    private final AddressService addressService;

    AddressController(AddressService addressService) {
        this.addressService = addressService;
    }

    /**
     * 获取所有的收货地址
     *
     * @return address list
     */
    @GetMapping("list")
    public Response getAddressAll(HttpServletRequest request) {
        return Response.success(addressService.getAddressAll((User) request.getAttribute("current_user")));
    }

    /**
     * 通过id查找收货地址
     *
     * @param request
     * @param id
     * @return address or null
     */
    @GetMapping("get")
    public Response getAddress(HttpServletRequest request, int id) {
        Address address = addressService.getAddressById((User) request.getAttribute("current_user"), id);
        if (address == null)
            return Response.failure("未找到对应的地址数据");

        return Response.success(address);
    }

    /**
     * 添加一个收货地址
     *
     * @param request
     * @param address
     * @return success or failure
     */
    @PostMapping("add")
    public Response insertAddress(HttpServletRequest request, @RequestBody Address address) {
        if (addressService.insertAddress((User) request.getAttribute("current_user"), address))
            return Response.success("添加成功");

        return Response.failure("添加失败");
    }

    /**
     * 修改收货地址
     *
     * @param request
     * @param address
     * @return success or failure
     */
    @PostMapping("modify")
    public Response updateAddress(HttpServletRequest request, @RequestBody Address address) {
        if (addressService.updateAddress((User) request.getAttribute("current_user"), address))
            return Response.success("修改成功");

        return Response.failure("修改失败");
    }

    /**
     * 删除收货地址
     *
     * @param request
     * @param id
     * @return success or failure
     */
    @GetMapping("remove")
    public Response deleteAddress(HttpServletRequest request, int id) {
        if (addressService.deleteAddress((User) request.getAttribute("current_user"), id))
            return Response.success("删除成功");

        return Response.failure("删除失败");
    }

    /**
     * 设置默认收货地址
     *
     * @param request
     * @param id
     * @return success or failure
     */
    @PostMapping("setDefault")
    public Response setDefaltAddress(HttpServletRequest request, int id) {
        if (addressService.setDefaultAddress((User) request.getAttribute("current_user"), id))
            return Response.success("设置成功");

        return Response.failure("设置失败");
    }
}
